import { View } from '@tarojs/components'
import { Tabs, Tab, ConfigProvider, Toast } from '@antmjs/vantui'
import useProfileStatusAction from '@/hooks/useProfileStatusAction';
import React, { useEffect, useState, Suspense } from 'react'
import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import { handleLoginCallback, showToast } from '@/common/util'
import { IResponseSuccess, IShopUserLogin, USER_PROFILE_STATUS } from '@/typing';
import { PAGE_PATH, RESPONSE_CODE, STORE_KEY } from '@/common/config';
import {  handleLoginAjax } from '@/common/service';
import useBlogAction from '@/hooks/useBlogAction';

import { observer } from 'mobx-react-lite';
import './index.scss'
// import { useStore } from '@/store';
const JoinFailDialog = React.lazy(() => import('@/components/joinFailDialog/joinFailDialog'));

const OrderDetailDialog = React.lazy(() => import('@/components/orderDetailDialog/orderDetailDialog'));
const EmptySmart = React.lazy(() => import('@/components/empty/empty'));


const PendingAndUnknown = React.lazy(() => import('@/components/pendingAndUnknown/pendingAndUnkown'));
const FinishedOrderItem = React.lazy(() => import('@/components/finishedOrderItem/finishedOrderItem'));
const ConversationOrderItem = React.lazy(() => import('@/components/conversationOrderItem/conversationOrderItem'));
const AcceptOrderItem = React.lazy(() => import('@/components/acceptOrderItem/acceptOrderItem'));
const ChatDialog = React.lazy(() => import('@/components/chatDialog/chatDialog'));

const Index: React.FC = () => {
  // const { regionStore, jobStore, serviceStore } = useStore()

  // const [orderStatus, setOrderStatus] = useState('0')
  const { acceptPage,
    waitPage,
    finishedPage,
    cancelPage, acceptOrderList,
    waitingOrderList,
    finishedOrderList,
    cancleOrderList, detailShow, orderDetail,
    chatDialogShow,
    wechat,
    mobile,
    tabIndex, setTabIndex,
    setChatDialogShow,
    setDetailShow, setAcceptPage,
    setWaitPage,
    setFinishedPage,
    setNoFinishedData,
    setNoAcceptData,
    setNoWaitingData,
    setNoCancelData,
    setCancelPage, handleResetData,handleWaitingOrderList,handleFinishedOrderList, handleInitAllTabList, handleCancelOrderList, handleAcceptOrderList, handleCancelOrderAction, handleShowCallAction, handleShowOrderAction, handleAcceptOrderAction, handleCompleteOrderAction
  } = useBlogAction()
  const [noticeShow, setNoticeShow] = useState(false)
const [userStatus, setUserStatus] = useState(USER_PROFILE_STATUS.unknown)
  const {  profileRemark, handleInitProfileStatus, handleInitProfileStatusPromise } = useProfileStatusAction()

  // let statusTimeout;
  const handleInitPage = (): Promise<{ mobile: string }> => {
   
    setCancelPage(1)
    setAcceptPage(1)

    return new Promise((resolve, reject) => {
      const storePhone = Taro.getStorageSync(STORE_KEY.PHONE) || '';

      if (storePhone) {
        resolve({
          mobile: storePhone
        })
      } else {
        Taro.login({
          success: async (res) => {
            if (res.code) {
              const loginRes = await handleLoginAjax(res.code) as IResponseSuccess<IShopUserLogin>
              if (loginRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {

                if (loginRes.data.code === RESPONSE_CODE.SUCCESS) {

                  const loginData = loginRes.data.data.userInfo
                  Taro.setStorageSync(STORE_KEY.USER_INFO, JSON.stringify(loginData))
                  Taro.setStorageSync(STORE_KEY.TOKEN, loginData.token)
                  Taro.setStorageSync(STORE_KEY.USER_ID, loginData.id)

                  resolve({
                    mobile: loginData.mobile
                  })


                } else if (loginRes.data.code === RESPONSE_CODE.ERROR) {
                  throw new Error("请求异常");

                }
                else {
                  showToast(loginRes.data.msg)
                }

              }
              else {
                showToast('服务器错误')
              }

            } else {
              showToast(res.errMsg)

            }
          }
        })
      }

    })

  }


  const handleTabChange = (e) => {

    const index = e.detail.index

    setTabIndex(index)
  }
  const handleInitPageAction = () => {
    // handleIndexInit().then
    handleInitPage().then(async (res) => {
      // await handleInitProfileStatus();
      if (res.mobile) {
        Taro.setStorageSync(STORE_KEY.PHONE, res.mobile)

        handleInitProfileStatusPromise().then(res => {
          if (res.code === RESPONSE_CODE.SUCCESS) {
            const status = res.data.status;
            setUserStatus(status)
            if (status === USER_PROFILE_STATUS.enable) {

              handleInitAllTabList()
            }
          }else if (res.code === RESPONSE_CODE.LOGIN_EXPIRE || res.code === RESPONSE_CODE.LOGIN_NEED) {
            handleLoginCallback(() => handleInitPageAction())
          }
        })



      } else {
        Taro.navigateTo({
          url: PAGE_PATH.LOGIN
        })
      }
    })

  }
  const handleInitShow = () => {
  
    handleInitProfileStatusPromise().then(res => {
      if (res.code === RESPONSE_CODE.SUCCESS) {
        const profileRes = res.data

        const status = profileRes.status;
        
        setUserStatus(status)
        if (status !== USER_PROFILE_STATUS.enable) {
          handleInitPage().then(async (res) => {
            if (res.mobile) {
              Taro.setStorageSync(STORE_KEY.PHONE, res.mobile)
             
              handleInitProfileStatus();


            } else {
              Taro.navigateTo({
                url: PAGE_PATH.LOGIN
              })
            }

          })
        } else {
          // handleInitProfileStatus();
          // Taro.setStorageSync(STORE_KEY.NOT_LOAD, 1)

          handleCancelOrderList(true)
          handleAcceptOrderList(true)
        }
        setNoticeShow(false)
        if (!noticeShow) {
          Taro.showTabBar()
        }
      } else if (res.code === RESPONSE_CODE.LOGIN_EXPIRE || res.code === RESPONSE_CODE.LOGIN_NEED) {
        handleLoginCallback(() => handleInitShow())
      }

    })




  }
  useDidShow(() => {
    handleInitShow()

  })
  useReachBottom(() => {
    if (Number(tabIndex) === 0) {
      const nextPage1 = acceptPage + 1;
      setAcceptPage(nextPage1)

    } else if (Number(tabIndex) === 1) {
      const nextPage2 = waitPage + 1;
      setWaitPage(nextPage2)

    } else if (Number(tabIndex) === 2) {
      const nextPage3 = finishedPage + 1;
      setFinishedPage(nextPage3)

    } else if (Number(tabIndex) === 3) {
      const nextPage4 = cancelPage + 1;
      setCancelPage(nextPage4)
    }
  });
  usePullDownRefresh(async () => {
    if(userStatus === USER_PROFILE_STATUS.enable){
      try {
        // Taro.setStorageSync(STORE_KEY.NOT_LOAD, 0)
        Toast.loading({
          message: '刷新中...',
          mask: true,
          forbidClick: true
        })
  
        handleResetData()
  
        setTimeout(async () => {
          // console.log(tabIndex)
          if(Number(tabIndex) === 0){
            setNoAcceptData(false)
            handleAcceptOrderList(true)
          }else if(Number(tabIndex) === 1){
            setNoWaitingData(false)
           
            handleWaitingOrderList(true)
          }else if(Number(tabIndex) === 2){
            setNoFinishedData(false)
            handleFinishedOrderList(true)
          }else if(Number(tabIndex) === 3){
            setNoCancelData(false)
            handleCancelOrderList(true)
          }
          // await handleInitAllTabList(true)
          Toast.clear()
        }, 1000);
        // await handleInitBlogerList(1, true);
      } catch (error) {
        Toast.clear()
  
      } finally {
        Taro.stopPullDownRefresh()
      }
    }else{
      Taro.stopPullDownRefresh()
    }
    
  });

  useEffect(() => {
    if (noticeShow || detailShow || chatDialogShow) {
      Taro.hideTabBar()
    } else {
      Taro.showTabBar()
    }

  }, [noticeShow, detailShow, chatDialogShow])
  useEffect(() => {

    handleInitPageAction()
    return () => {
      // clearTimeout(statusTimeout)
    }

  }, [])

  return (
    <>
      {/* {regionStore.regionDataT} */}
      {userStatus !== USER_PROFILE_STATUS.loading && <View className='min-h-100vh bg-#F6F6F6 index box-border'>

        {userStatus === USER_PROFILE_STATUS.enable && <ConfigProvider themeVars={{ primaryColor: '#333333', tabsBottomBarHeight: '8rpx', tabsNavBackgroundColor: '#F6F6F6' }}>
          <Tabs active={tabIndex} swipeable sticky={true} ellipsis={false} animated={true} titleActiveColor='#333333' titleInactiveColor='#333333' onChange={handleTabChange} >
            <Tab title={`待接单${acceptOrderList.length > 0 ? `(${acceptOrderList.length})` : ''}`} name='0'>
              <Suspense>
                {acceptOrderList.length > 0 ? <>
                  {acceptOrderList.map((item, index) => {
                    return <AcceptOrderItem orderInfo={item} key={index} orderIndex={index} handleCancelOrder={handleCancelOrderAction} handleAcceptOrder={handleAcceptOrderAction} handleShowOrder={handleShowOrderAction}></AcceptOrderItem>
                  })
                  }
                </> : <EmptySmart></EmptySmart>}
              </Suspense>



            </Tab>
            <Tab title={`已接单${waitingOrderList.length > 0 ? `(${waitingOrderList.length})` : ''}`} name='1'>
              <Suspense>
                {waitingOrderList.length > 0 ? <>
                  {waitingOrderList.map((item, index) => {
                    return <ConversationOrderItem key={index} orderInfo={item} orderIndex={index} handleShowOrder={handleShowOrderAction} handleShowCall={handleShowCallAction} handleCompleteOrder={handleCompleteOrderAction}></ConversationOrderItem>
                  })
                  }
                </> : <EmptySmart></EmptySmart>}
              </Suspense>


            </Tab>
            <Tab title={`已完成${finishedOrderList.length > 0 ? `(${finishedOrderList.length})` : ''}`} name='2'>
              <Suspense>  {finishedOrderList.length > 0 ? <>
                {finishedOrderList.map((item, index) => {
                  return <FinishedOrderItem key={index} orderInfo={item} handleShowOrder={handleShowOrderAction}></FinishedOrderItem>
                })
                }
              </> : <EmptySmart></EmptySmart>}</Suspense>


            </Tab>
            <Tab title={`已取消${cancleOrderList.length > 0 ? `(${cancleOrderList.length})` : ''}`} name='-1'>
              <Suspense>{cancleOrderList.length > 0 ? <>
                {cancleOrderList.map((item, index) => {
                  return <FinishedOrderItem key={index} orderInfo={item} handleShowOrder={handleShowOrderAction} ></FinishedOrderItem>
                })
                }
              </> : <EmptySmart></EmptySmart>}</Suspense>


            </Tab>
          </Tabs>
        </ConfigProvider>}

        {userStatus === USER_PROFILE_STATUS.disable && <JoinFailDialog profileRemark={profileRemark} noticeShow={noticeShow} handlePopStatus={(popStatus) => setNoticeShow(popStatus)}></JoinFailDialog>}

        {(userStatus === USER_PROFILE_STATUS.unknown || userStatus === USER_PROFILE_STATUS.pending) && <PendingAndUnknown userProfileStatus={userStatus} noticeShow={noticeShow} handlePopStatus={(popStatus) => setNoticeShow(popStatus)}></PendingAndUnknown>}


        <ChatDialog mobile={mobile} wechat={wechat} show={chatDialogShow} handlePopStatus={(popStatus) => setChatDialogShow(popStatus)} ></ChatDialog>


        {orderDetail && <OrderDetailDialog show={detailShow} handlePopStatus={(status) => setDetailShow(status)} orderInfo={orderDetail}></OrderDetailDialog>}



      </View>}
    </>

  )
}
export default observer(Index);
